package com.ee.chat.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IDynamicService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.UserDynamicMapper;
import com.ee.chat.common.entity.AdminUser;
import com.ee.chat.common.entity.UserDynamic;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.service.IPushMessageService;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.ali.oss.OSSUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class DynamicService implements IDynamicService {
    @Resource
    UserDynamicMapper userDynamicMapper;
    @Resource
    IOperationService operationService;
    @Resource
    IPushMessageService pushMessageService;
    @Resource
    MyAliOSSConfig aliOSSConfig;

    /**
     * 动态审核列表
     * @Author Shane
     * @Date 2019/10/2319:30
     * @param
     * @return
     **/
    @Override
    public Result list(HttpServletRequest request, Integer userId, Integer status, String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && userId == null && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/audit/dynamic/viewList")){
                data.put("hostDynamics", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userDynamicMapper.list(p, userId, status, beginTime, endTime);
        List<Map<String, Object>> hostDynamics = iPage.getRecords();
        for(Map<String, Object> dynamic : hostDynamics){
            List<String> url = JSONArray.parseArray(dynamic.get("url")+"", String.class);
            dynamic.put("url", url);
        }

        data.put("hostDynamics", hostDynamics);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询动态审核列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 审核
     * @Author Shane
     * @Date 2019/10/2319:31
     * @param id        动态id
     * @param status    状态，1-通过  2-拒绝
     * @param reason    理由
     * @return
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result audit(HttpServletRequest request, Integer id, Integer status, Integer type, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserDynamic userDynamic = userDynamicMapper.selectById(id);
        if(userDynamic.getAuditStatus() != 0){
            return Result.returnFailure("该记录已经审核，不能重复审核");
        }

        UserDynamic dynamic = new UserDynamic();
        dynamic.setId(userDynamic.getId());
        dynamic.setCover(userDynamic.getCover());
        dynamic.setUrl(userDynamic.getUrl());
        dynamic.setAuditStatus(status);
        dynamic.setAuditUserId(userId);
        if(status == 2){
            dynamic.setReason(userDynamic.getReason()==null ? reason : userDynamic.getReason()+"\n"+reason);
        }

        List<String> files = new ArrayList<>();
        Map<String, String> push = new HashMap<>();
        if(status == 1){
            operationService.addOperationLog(request, "审核通过"+ userDynamic.getUserId()+"用户发布的动态"+ userDynamic.getId());

            push.put("title", "动态发布审核通过");
            push.put("content", "您发布的动态已通过审核，请注意查看");

        }else{
            operationService.addOperationLog(request, "审核拒绝"+ userDynamic.getUserId()+"用户发布的动态"+ userDynamic.getId());

            push.put("title", "动态发布审核驳回");
            push.put("content", "您发布的动态审核被驳回，原因：" + reason);

            //获取源文件
            if(type == 1){
                if(!StringUtil.isEmpty(userDynamic.getCover())){
                    files.add(userDynamic.getCover());
                    dynamic.setCover(null);
                }
                List<String> url = JSONArray.parseArray(userDynamic.getUrl(), String.class);
                if(url != null && url.size() > 0){
                    files.addAll(url);
                    dynamic.setUrl(null);
                }
            }
        }
        userDynamicMapper.updDynamicById(dynamic);

        push.put("type", "4");
        pushMessageService.pushGeneralMessage(userDynamic.getUserId(), push);

        //删除OSS文件
        if(files != null && files.size() > 0) {
            OSSUtil.deleteFile(aliOSSConfig, files);
        }

        return Result.returnSuccess(null);
    }

    /**
     * 撤销主播动态审核
     * @Author AppiJ
     * @Date 2021/1/5 15:32
     * @param id        动态id
     * @param reason    理由
     * @return
     */
    @Override
    public Result cancelAudit(HttpServletRequest request, Integer id, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserDynamic userDynamic = userDynamicMapper.selectById(id);
        if(userDynamic.getAuditStatus() == 0){
            return Result.returnFailure("该记录未审核，无法撤销审核");
        }

        UserDynamic dynamic = new UserDynamic();
        dynamic.setId(userDynamic.getId());
        dynamic.setCover(userDynamic.getCover());
        dynamic.setUrl(userDynamic.getUrl());
        dynamic.setAuditStatus(0);
        dynamic.setAuditUserId(userId);
        dynamic.setReason(userDynamic.getReason()+"\n"+reason);
        userDynamicMapper.updDynamicById(dynamic);

        operationService.addOperationLog(request, "撤销审核"+ userDynamic.getUserId()+"用户发布的动态"+ userDynamic.getId());

        Map<String, String> push = new HashMap<>();
        push.put("title", "撤销动态发布审核");
        push.put("content", "您发布的动态审核已被撤销，请耐心等待重新审核，原因：" + reason);
        push.put("type", "4");
        pushMessageService.pushGeneralMessage(userDynamic.getUserId(), push);

        return Result.returnSuccess(null);
    }
}
